﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace iTunesExport.Parser
{    
    public class TrackCollection
    {
        private readonly string type;
        private long sizeMb;
        private int missingTracks;
        private readonly List<Track> tracks = new List<Track>();
 
        public TrackCollection(string name, string type)
        {
            Name = name;
            this.type = type;
        }

        #region properties

        public string Name { get; set; }

        public string Type { get { return type; } }
        public int Count { get { return tracks.Count; } }
        public long Size { get { return sizeMb; } }
        public int MissingTracks { get { return missingTracks; } }
        public void Add(Track t) { tracks.Add(t); }
        public IEnumerable<Track> Tracks{ get { return tracks; } }
        #endregion

        public override string ToString()
        {
            return Name;            
        }
        public string ToStringDetailed(bool withTracks)
        {
            var sb = new StringBuilder();
            sb.AppendLine(string.Format("{0} {1} tracks {2} MB", Name, Count, Size));
            if (withTracks)
            {
                foreach (Track t in tracks)
                {
                    sb.AppendLine(t.Location);
                }
            }
            return sb.ToString();
        }

        public void Clear()
        {
            tracks.Clear();
        }

        public void GetInfo()
        {
            if (sizeMb > 0)
                return;
            Refresh();
        }

        public void Refresh()
        {
            sizeMb = 0;
            missingTracks = 0;
            foreach (Track t in tracks)
            {
                if (File.Exists(t.Location))
                    sizeMb += (new FileInfo(t.Location)).Length;
                else
                    missingTracks++;
            }
            sizeMb >>= 20;
        }

        public TrackCollection Randomize()
        {
            var newTc = new TrackCollection(Name, Type);
            var tmpTracks = new List<Track>(tracks);
            for (var r = new Random(); tmpTracks.Count > 0; )
            {
                int index = r.Next(tmpTracks.Count);
                newTc.Add(tmpTracks[index]);
                tmpTracks.RemoveAt(index);
            }
            return newTc;
        }
    }    
}
